import React, { useState, useEffect } from 'react';
import axios from 'axios'
import {
    Table,
    Popconfirm,
    Button,
    Space,
} from 'antd';
import FromAddAndUpdate from './FromAddAndUpdate';
import ModalDemo from './Modal';

const ModalAddFromAddTable = () => {
    const columns = [
        {
            title: '序号',
            width: 42,
            align: 'center',
            key: 'xuhao',
            fixed: 'left',
            render: (text, record, index) => `${index + 1}`,  //每一页都从1开始

            // 每一页都累计开始
            // render: (text, record, index) => `${(pagination.current - 1) * (pagination.pageSize) + (index + 1)}` 
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
        },
        {
            title: '周几',
            dataIndex: 'week',
            key: 'week',
        },
        {
            title: '空气质量',
            align: 'center',
            dataIndex: 'air_level',
            key: 'air_level',
        },
        {
            title: '风力等级',
            dataIndex: 'win_speed',
            key: 'win_speed',
        },
        {
            title: '风向',
            dataIndex: 'win',
            key: 'win',
        },
        {
            title: '天气',
            dataIndex: 'wea',
            key: 'wea',
        },
        {
            title: '最高温度',
            dataIndex: 'tem1',
            key: 'tem1',
        },
        {
            title: '最低温度',
            dataIndex: 'tem2',
            key: 'tem2',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            key: 'operation',
            width: 120,
            render: (_, record) => (
                <>
                    <Popconfirm title="确定要删除吗?" onConfirm={() => handleDeleteTableRows(record.key)}>
                        {/* <a href='/#'>Delete {record.date} </a> */}
                        <a href='/#'>Delete</a>
                    </Popconfirm>
                    <Button type="link" onClick={() => edit(record)}>Update</Button>
                </>
            )

        }
    ];
    //删除行
    const handleDeleteTableRows = (key) => {
        const newData = dataSource.filter((item) => item.key !== key);
        setDataSource(newData);
    };
    //编辑行
    const edit = (record) => {
        setDataTitle('编辑')
        record.uuid = new Date().getTime()
        // record.dateTem = record.date
        setDataRow(record)
        setOpen(true);
    };

    //展示表格数据
    const [dataSource, setDataSource] = useState([]);
    //存储选中行的key值
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    //子模块Modal打开或关闭的状态
    const [open, setOpen] = useState(false);
    //Modal标题
    const [dataTitle, setDataTitle] = useState('');
    const [dataRow, setDataRow] = useState({});


    //选中行的事件
    const onSelectChange = (newSelectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys, selectedRows);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    //选中行的配置
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    //判断选中的行数是否大于0，决定删除按钮是否可用
    const hasSelected = selectedRowKeys.length > 0;

    const dataAxios = () => {
        axios.get('https://www.tianqiapi.com/api', {
            params: {
                appid: 23035354,
                appsecret: '8YvlPNrz',
                version: 'v9',
                cityid: 0,
                city: '太原',
                ip: 0,
                callback: 0
            }
        })
            .then(response => {
                let { data } = response.data
                //动态加 key
                data.forEach((element, i) => {
                    element.key = 'key' + i
                });
                setDataSource(data);
            })
            .catch(error => {
                console.log(error);
            });
    }

    useEffect(() => {
        dataAxios();
        console.log('dataAxios()请求数据,useEffect()方法')
    }, []);

    const handleAddRowOpenModal = (e) => {
        // console.log('add', e.target.innerText)
        setDataTitle('添加')
        setOpen(true);
    }
    //子模块调用
    const handleModalClose = () => {
        setOpen(false);
    }
    //子模块调用,添加个修改
    const handleAddTableRow = (newRowDate) => {
        console.log(newRowDate)
        const index = dataSource.findIndex((item) => newRowDate.key === item.key);
        if (index > -1) {
            //修改
            dataSource.splice(index, 1, newRowDate);
            setDataSource([...dataSource]);
        } else {
            //添加
            newRowDate.key = new Date().getTime()
            setDataSource([newRowDate, ...dataSource]);
        }

    }

    return (
        <>
            <h3>Hooks:Table+Modal+From</h3>
            <Space wrap style={{
                marginBottom: 4,
            }}>
                <Button type="primary" onClick={handleAddRowOpenModal}>
                    添加
                </Button>
                <ModalDemo></ModalDemo>
                <Button type="primary" danger disabled={!hasSelected} >
                    Delete SelectRows
                </Button>

                {hasSelected ? `选中 ${selectedRowKeys.length} 行` : ''}
            </Space>

            <Table
                bordered
                rowSelection={rowSelection}
                dataSource={dataSource}
                columns={columns}
                pagination={{
                    hideOnSinglePage: true,     //只有一页时是否隐藏分页器
                    showSizeChanger: true,      //显示每页多少条的下拉框
                    showQuickJumper: true,      //显示跳转到多少页
                }}
                scroll={{
                    x: 1200,
                }}
            />

            <FromAddAndUpdate
                openModal={open}
                handleModalClose={handleModalClose}
                dataTitle={dataTitle}
                dataRow={dataRow}
                handleAddTableRow={handleAddTableRow}
            ></FromAddAndUpdate>


        </>
    )

}

export default ModalAddFromAddTable